import Vue from 'vue'
import VueRouter from 'vue-router'
// import { CONFIGURABLE } from 'core-js/internals/function-name'
// import { component } from 'vue/types/umd'
import {getUser, refreshUserToken} from "@/utils/storage";

Vue.use(VueRouter)
//获取原型对象上的push函数
const originalPush = VueRouter.prototype.push
//修改原型对象中的push方法
VueRouter.prototype.push = function push(location) {
    return originalPush.call(this, location).catch((err) => err)
}
let routes = [
	{
		path: '/',
		redirect: '/front/home'
	},
	{
		path: '/front',
		name: 'Front',
		component: () => import('../layout/front'),
		children: [
			{
				path: 'home',
				name: 'FrontHome',
				component: () => import('../views/front/home'),
				meta:{
					title:'首页 - 每一步，皆是风尚之选'
				}
			},
			{
				//配置路径参数后 刷新搜索页面后搜索框仍会保留上次的内容
				// path: 'search/:input/:selection',
				path: 'search',
				name: 'Search',
				component: () => import('../views/front/search'),
				meta:{
					title: '搜索 - 开启您的寻鞋之旅'
				}
			},
			{
				path: 'goods',
				name: 'Goods',
				component: () => import('../views/front/goods'),
				// meta:{
				//	由于要在标题中显示商品详情页的title并且与商品相关，所以页面标题改在goods组件中设置
				// }
			},
			{
				path: 'cart',
				name: 'Cart',
				component: () => import('../views/front/cart'),
				meta:{
					title:'选购清单 - 购物车满载，时尚启程'
				}
			},
			{
				path: 'preOrder',
				name: 'PreOrder',
				component: () => import('../views/front/preOrder'),
				meta:{
					title:'确认订单 - 结算无忧，快速便捷'
				}
			},
			{
				path:'pay:aliPay?',
				name:'Pay',
				component:()=>import('../views/front/pay'),
				meta: {
					title:'支付 - 安全支付，购物更安心'
				}
			},
			{
				path: 'order',
				name: 'FrontOrder',
				component: () => import('../views/front/order'),
				meta:{
					title:'我的订单 - 订单追踪，一目了然'
				}
			},
			// {
			// 	path: 'collect',
			// 	name: 'Collect',
			// 	component: () => import('../views/front/collect')
			// },
			{
				path: 'person',
				name: 'Person',
				component: () => import('../views/front/person'),
				meta:{
					title:'我的 - 个人中心，专属体验'
				}
			},
			{
				path: 'address',
				name: 'Address',
				component: () => import('../views/front/address'),
				meta:{
					title:'我的地址 - 地址管理，轻松编辑'
				}
			},
			{
				path:'success',
				name:'Success',
				component:()=>import('../views/front/success'),
				meta:{
					title:'支付成功 - 支付成功，感谢您的信任'
				}
			}
		]
	},
	{
		path: '/login',
		name: 'Login',
		component: () => import('../views/login'),
		meta:{
			title:'登录 - 轻松登录，畅游鞋海'
		}
	},
	{
		path: '/register',
		name: 'Register',
		component: () => import('../views/register'),
		meta:{
			title:'注册 - 加入我们，享受更多优惠'
		}
	},
	{
		path: '/protocol',
		name: 'Protocol',
		component: () => import('../views/protocol'),
		meta:{
			title:'用户协议 - 用户协议与隐私政策'
		}
	}
]

const createRouter = () =>
    new VueRouter({
        mode: 'history',
        routes: routes,
    })

const router = createRouter()

let user = getUser()
resetRouter(user.permission)

//写一个重置路由的方法，切换用户后，或者退出时清除动态加载的路由
export function resetRouter(permissions) {
    if (permissions) {
        const newRouter = createRouter()
        router.matcher = newRouter.matcher // 新路由实例matcer，赋值给旧路由实例的matcher，（相当于replaceRouter）
        if (!router.getRoutes().find((v) => v.name === 'Manage')) {
            router.addRoute(getPermissions(permissions))
        }
    }
}

// old
// function getPermissions(permissions) {
//     let manage = {
//         path: '/manage', name: 'Manage', component: () => import("../layout/manage"),
//         children: [
//             {path: 'person', name: '个人信息', component: () => import("../views/manage/person")}
//         ]
//     }
//     // 设置路由菜单
//     if (permissions) {
//         permissions.forEach(item => {
//             manage.children.push({
//                 path: "/manage" + item.path,
//                 name: item.name,
//                 component: () => import("../views/manage" + item.path)
//             });
//         })
//     }
//     console.log(manage)
//     return manage
// }
// new
function getPermissions(permissions) {
    let manage = {
        path: '/manage',
        name: 'Manage',
        component: () => import('../layout/manage'),
        children: [
            {
                path: 'person',
                name: '个人信息',
                meta: {title: '个人中心'},
                component: () => import('../views/manage/person')
            }
        ]
    }
    // 设置路由菜单
    if (permissions) {
        permissions.forEach((item) => {
            let obj = {
                path: '/manage' + item.path,
                name: item.name,
                meata: {title: item.name},
                component: () => import('../views/manage' + item.path)
            }
            if (item.path.includes('/order')) {
                (obj.redirect = '/manage/order/all'),
                    (obj.children = [
                        {
                            path: '/manage/order/all',
                            name: 'AllOrder',
                            meta: {title: '全部订单'},
                            component: () => import('@/components/stateOrder/allOrder.vue')
                        },
                        {
                            path: '/manage/order/unPay',
                            name: 'UnPayOrder',
                            meta: {title: '未支付'},
                            component: () => import('@/components/stateOrder/unpayOrder.vue')
                        },
                        {
                            path: '/manage/order/preDelivery',
                            name: 'PreDeliveryOrder',
                            meta: {title: '代发货'},
                            component: () => import('@/components/stateOrder/preDeliveryOrder.vue')
                        },
                        {
                            path: '/manage/order/delivery',
                            name: 'DeliveryOrder',
                            meta: {title: '运输中'},
                            component: () => import('@/components/stateOrder/deliveryOrder.vue')
                        },
                        {
                            path: '/manage/order/preReceive',
                            name: 'PreReceiveOrder',
                            meta: {title: '已到达'},
                            component: () => import('@/components/stateOrder/preReceiveOrder.vue')
                        },
                        {
                            path: '/manage/order/received',
                            name: 'ReceiveOrder',
                            meta: {title: '已完成'},
                            component: () => import('@/components/stateOrder/receiveOrder.vue')
                        },
                        {
                            path: '/manage/order/preReturn',
                            name: 'PreReturnOrder',
                            meta: {title: '申请退货单'},
                            component: () => import('@/components/stateOrder/preReturnOrder.vue')
                        },
                        {
                            path: '/manage/order/return',
                            name: 'ReturnOrder',
                            meta: {title: '退货单'},
                            component: () => import('@/components/stateOrder/returnOrder.vue')
                        },
                    ])
            }
            manage.children.push(obj)
        })
    }
    return manage
}

router.beforeEach((to, from, next) => {
	//如果去的是登录或注册页或者刚刚从登录页过来，不刷新token
	//去协议页面，不刷新token
	if (
		to.path.includes('home') ||
		to.path.includes('login') ||
		to.path.includes('register') ||
		from.path.includes('login') ||
		to.path.includes('protocol')
	) {
		next()
	} else {
		refreshUserToken().then(res=>{
			if (res.code === '0'){
				next()
			}
		})
	}
	document.title = to.meta.title ?? '逸足轩鞋城，心仪鞋款尽在指尖'
})


export default router
